﻿using System.Collections.Generic;
using System.Linq;

namespace dPet.Domain.Models
{
	using Hangerd;
	using Hangerd.Entity;

	public class ServiceSKUProperty : EntityBase
	{
		#region Public Properties

		/// <summary>
		/// 所属医院ID
		/// </summary>
		public string HospitalId { get; private set; }

		/// <summary>
		/// 服务类别
		/// </summary>
		public ServiceCategory Category { get; private set; }


		private string _frontendName;

		/// <summary>
		/// SKU属性前台名称
		/// </summary>
		[RecordModify]
		public string FrontendName
		{
			get { return _frontendName; }
			set
			{
				if (string.IsNullOrWhiteSpace(value))
				{
					throw new HangerdException("SKU属性前台名称不可为空");
				}

				_frontendName = value.Trim();
			}
		}


		private string _backendName;

		/// <summary>
		/// SKU属性后台名称
		/// </summary>
		[RecordModify]
		public string BackendName
		{
			get { return _backendName; }
			set
			{
				if (string.IsNullOrWhiteSpace(value))
				{
					throw new HangerdException("SKU属性后台名称不可为空");
				}

				_backendName = value.Trim();
			}
		}

		public virtual ICollection<ServiceItem> ServiceItems { get; private set; }

		/// <summary>
		/// 属性可选值
		/// </summary>
		public virtual ICollection<ServiceSKUPropertyValue> Values { get; private set; }

		#endregion

		#region Constructors

		private ServiceSKUProperty() { }

		public ServiceSKUProperty(Hospital hospital, string frontendName, string backendName)
		{
			this.HospitalId = hospital.Id;
			this.FrontendName = frontendName;
			this.BackendName = backendName;
			this.Values = new List<ServiceSKUPropertyValue>();
		}

		#endregion

		#region Public Methods

		/// <summary>
		/// 增加SKU属性值
		/// </summary>
		public void AddValue(string value)
		{
			var existValue = this.GetExistValue(value);

			if (existValue != null)
			{
				throw new HangerdException("SKU属性: {0}, 已存在属性值: {1}", this.BackendName, value);
			}

			this.Values.Add(new ServiceSKUPropertyValue(this, value));
		}

		/// <summary>
		/// 增加SKU属性值
		/// </summary>
		public void UpdateValue(string valueId, string newValue)
		{
			var existValue = this.GetExistValue(newValue);

			if (existValue != null && existValue.Id != valueId)
			{
				throw new HangerdException("SKU属性: {0}, 已存在属性值: {1}", this.BackendName, newValue);
			}

			var currentValue = this.Values.FirstOrDefault(pv => pv.Id == valueId);

			if (currentValue == null)
			{
				throw new HangerdException("SKU属性: {0}, 不存在属性值Id: {1}", this.BackendName, valueId);
			}

			currentValue.SetValue(newValue);
		}

		/// <summary>
		/// 设置类别
		/// </summary>
		public void Categorize(ServiceCategory category)
		{
			this.Category = category;
		}

		#endregion

		#region Private Methods

		private ServiceSKUPropertyValue GetExistValue(string value)
		{
			return this.Values
				.FirstOrDefault(pv => pv.Value == value);
		}

		#endregion
	}
}
